<template>
    <div style="border: 1px solid #ccc;padding: 20px; margin: 10px;">
    <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>角色列表管理</el-breadcrumb-item>
  </el-breadcrumb>
  </div>

   <div style="border: 1px solid #ccc;padding: 20px; margin: 10px;">
    <el-button type="success" @click="AddNoe">新增角色</el-button>
        <el-table :data="tableData" style="width: 100%">
        <el-table-column fixed prop="id" label="编号" width="180" />
        <el-table-column prop="roleName" label="角色名称" width="180" >
             <template #default="scope">
                <el-span style="color: blue;"  @click="toDetail(scope.row)">{{scope.row.roleName}}</el-span>
             </template>
        </el-table-column>
        <el-table-column prop="creater" label="创建人" width="180" />
        <el-table-column prop="createTime" label="创建日期" width="180" >
             <template #default="scope">
                {{moment(scope.row.createTime).format("YYYY-MM-DD HH:mm:ss")}}
             </template>
        </el-table-column>
        <el-table-column prop="updater" label="修改人" width="180" />
        <el-table-column prop="updateTime" label="修改日期" width="180" >
            <template #default="scope">
             {{ scope.row.updateTime ? moment(scope.row.updateTime).format("YYYY-MM-DD HH:mm:ss") : '' }}
            </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="230px">
        <template #default="scope">
            <el-button  type="danger" size="small" @click="remove(scope.row.id)">删除</el-button>
            <el-button  type="primary" size="small" @click="update(scope.row)">修改</el-button>
            <el-button  type="primary" size="small" @click="Fenpei(scope.row)">分配人员</el-button>
        </template>
        </el-table-column>
    </el-table>
    <!-- 添加角色 -->
     <el-dialog v-model="dialogVisible"title="新增" width="800">
        <el-form
            ref="ruleFormRef"
            style="max-width: 600px"
            :model="ruleForm"
            :rules="rules"
            label-width="auto"
        >
            <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="ruleForm.roleName" />
            </el-form-item>
            <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                保存
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
     </el-dialog>
      <!-- 修改角色 -->
     <el-dialog v-model="UpdialogVisible"title="修改" width="800">
        <el-form
            ref="ruleFormRef"
            style="max-width: 600px"
            :model="ruleForm"
            :rules="rules"
            label-width="auto"
        >
            <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="ruleForm.roleName" />
            </el-form-item>

            <el-form-item>
            <el-button type="primary" @click="UpsubmitForm(ruleFormRef)">
                更新
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
     </el-dialog>
     <!-- 分配人员弹窗 -->
      <el-dialog v-model="FpdialogVisible"  width="500px" >
        <template #header="{ close, titleId, titleClass }">
         <div class="my-header">
          <h4 :id="titleId" :class="titleClass">请设置【<el-span style="color:red" v-model="roledata">{{roledata.rolename}}</el-span>】角色的员工</h4>
        <el-form :inline="true">
          <!-- 部门树 -->
        <el-form-item :label-width="180">
              <el-tree
                style="max-width: 600px"
                :data="data"
                :props="defaultProps"
                highlight-current="false"
                default-expand-all="false"
                @node-click="handleNodeClick"
                :default-expanded-keys="[currentDepartmentId]"
                :current-node-key="currentDepartmentId"
              />
        </el-form-item :label-width="180">
        <!-- 员工树 -->
        <el-form-item  :label-width="180">
            <el-tree
            style="max-width: 600px"
            :data="Empuser"
            show-checkbox
            node-key="id"
            ref="treeRef"
            :default-expanded-keys="[2, 3]"
            :props="defaultProps"
          />
        </el-form-item>      
          <el-form-item style="margin-top: 200px;">
                <el-button type="primary" @click="SaveRole()">
                    保存
                </el-button>
                <el-button>取消</el-button>
          </el-form-item>
         </el-form>
        </div>
       </template>
      </el-dialog>
      <!-- 角色名称详情 -->
      <el-dialog v-model="DetaildialogVisible"title="角色信息" width="500">
        <template #header="{ close, titleId, titleClass }">
         <div class="my-header">
          <h2 :id="titleId" :class="titleClass">属于角色【<el-span style="color:red" v-model="RoleDetail">{{RoleDetail.rolename}}</el-span>】的员工如下:</h2>
          <!-- 员工标签 -->
            <el-tag  size="large" v-for="tag in RoleUserData":key="tag.id"  closable :disable-transitions="false"   @close="handleClose(tag)" >{{tag.userName }} </el-tag>
            <el-button type="success" @click="AddNew()" style="margin-left: 100px;">+ New</el-button> 
          </div>
       </template>
      </el-dialog>
   </div>
</template>

<script setup lang="ts">
import axios from 'axios'
import moment  from 'moment'
import {ref,reactive, onMounted,nextTick}from 'vue'
import { ElMessage, type FormInstance, type FormRules ,ElMessageBox} from 'element-plus'
import type { TreeNode, TreeNodeData ,TreeInstance} from 'element-plus'
import { Read,Write } from '@/http/interceptors'


//#region 获取角色列表
const tableData=ref([])
onMounted(()=>{
GetRole();
})
const GetRole=()=>{
    Read.get("/api/UserGetRoleList",{}).then(res=>{
        tableData.value=res.data.data
    })
}
//#endregion

//#region 添加角色

const dialogVisible = ref(false)

const AddNoe=()=>{
  dialogVisible.value=true
  ruleForm.roleName=""
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  roleName: '',
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
  roleName: [
    { required: true, message: '角色名称不能为空', trigger: 'blur' },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      Write.post("/api/RoleCreateRole",ruleForm).then(res=>{
        if(res.data.code==200)
        {
            ruleForm.roleName="";
            dialogVisible.value=false;
            GetRole();
            ElMessage.success(res.data.message)
        }
        else{
            ElMessage.error(res.data.message)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
//#endregion

//#region   删除
const remove=(id:any)=>{
      ElMessageBox.confirm(
    '确认删除吗?',
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      Write.delete("/api/RoleDeleteRole",{params:{id:id}}).then(res=>{
        if(res.data.code==200)
        {
          ElMessage.success(res.data.message)
           GetRole();
        }
        else
        {
           ElMessage.error(res.data.message)
        }
      })

    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除操作已取消',
      })
    })
}

//#endregion

//#region  修改

const UpdialogVisible=ref(false)

const update=(row:any)=>{
    UpdialogVisible.value=true;
    Object.assign(ruleForm,row);
}


const UpsubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      Write.put("/api/RoleUpdateRole",ruleForm).then(res=>{
        if(res.data.code==200)
        {
            ruleForm.roleName=="";
            UpdialogVisible.value=false;
            GetRole();
            ElMessage.success(res.data.message)
        }
        else{
            ElMessage.error(res.data.message)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}


//#endregion

//#region   分配人员
const FpdialogVisible=ref(false)

//反填角色绑定值
const roledata=reactive({
    rolename:'',
    roleId:0,
    UserId:''
})

//分配角色方法
const Fenpei=(row:any)=>{
    FpdialogVisible.value=true;
    roledata.rolename=row.roleName
    roledata.roleId=row.id

    //先清空遍历的员工值和部门值
    Empuser.value = [];
    nextTick(() => {
        treeRef.value?.setCheckedKeys([]);
    });
   GetRoleUsers(row.id)//反填获取用户列表方法

}



//部门信息树
interface Tree {
  [key:string]:any
}

const treeRef = ref<TreeInstance>()

const handleNodeClick = (data: Tree) => {
  console.log(data)
  GetEmpuser(data.id)
}

const defaultProps = {
  label: 'label',
  children:'children'
}

const data: Tree[] = [
  {
    label:'请选择部门',
    children:[
       {id:1,label: 'IT信息部',},
      {id:2,label: '人力资源部',},
      {id:3,label: '销售部',},
      {id:4,label: '财务部',},
    ]
  }
]

//根据部门Id遍历员工信息
const Empuser=ref<any>([])  //遍历出的员工信息
const GetEmpuser=(id:any)=>{
    Read.get("/api/UserGetUserEmp",{params:{deparmentId:id}}).then(res=>{
        Empuser.value=res.data.data
        //然后调用 setCheckedKeys 方法，将所有已分配的用户（不仅仅是当前部门的）设置为选中状态。
         nextTick(() => {
             if (treeRef.value) {
                const userIds = RoleUserData.map(u => u.id)
                treeRef.value.setCheckedKeys(userIds, false)
             }
        })
    })
}

//保存角色方法

//保存角色
const SaveRole =()=>{
    roledata.UserId =treeRef.value!.getCheckedKeys(false).toString();//获取
    console.log(roledata.UserId)
    Write.post("/api/RoleSaveUserRole",roledata).then(res=>{
     if(res.data.code==200)
        {
            FpdialogVisible.value=false
            Empuser.value=[]
            GetRole();
            ElMessage.success(res.data.message)
        }
        else{
            ElMessage.error(res.data.message)
        }
  })
}
///===============================================
//定义的部门Id
const currentDepartmentId = ref()
 //反填数据
    const RoleUserData=reactive([{
          "id":0,
          "userName":'',
          "deparmentId":0
    }])
// 获取角色已分配的用户(反填)
const GetRoleUsers = (roleId: any) => {
    Read.get("/api/UserGetRoleUsers", { params: { roleId: roleId } }).then(res => {
        if (res.data.code == 200) {
          roledata.UserId=res.data.data.id
          //取第一个用户所在的部门ID，并调用 GetEmpuser 方法来加载该部门下的所有员工。
            RoleUserData.splice(0, RoleUserData.length, ...res.data.data)
            if (RoleUserData.length > 0) {
                GetEmpuser(RoleUserData[0].deparmentId)//获取部门Id调用加载员工方法
                currentDepartmentId.value=RoleUserData[0].deparmentId  //传递部门Id
                
            }
        }
    })
}
//=============================修改====================
//#endregion

//#region   角色人员详情


const DetaildialogVisible=ref(false)//弹窗
//角色名称详情
const RoleDetail=reactive({
    rolename:'',
    roleId:0,
    userId:0,
    userName:""
})
//点击名称详细方法
const toDetail=(row:any)=>{
    DetaildialogVisible.value=true
    RoleDetail.rolename=row.roleName
    RoleDetail.roleId=row.id
    GetRoleUsers(row.id)
}

///删除
const RemoveData=reactive({
  RoleId:0,
  UserId:0,
})
const handleClose = (tag:any) => {
  RemoveData.UserId=tag.id
  RemoveData.RoleId=RoleDetail.roleId
  RoleUserData.splice(RoleUserData.indexOf(tag), 1)
  Write.delete("/api/UserDeleteSingEmp",{params:RemoveData}).then(res=>{
    if(res.data.code==200)
    {
      DetaildialogVisible.value=false
      GetRole();
      ElMessage.success(res.data.message)
    }
    else{
      ElMessage.error(res.data.message)
    }
  })

}

//新增员工
const AddNew=()=>{
FpdialogVisible.value=true
roledata.roleId=RoleDetail.roleId
roledata.rolename=RoleDetail.rolename
}

//#endregion


</script>

<style scoped>

</style>